#include "account_mgr.h"

#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/warning.h>
#include <cppconn/metadata.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/resultset.h>
#include <cppconn/resultset_metadata.h>
#include <cppconn/statement.h>
#include <mysql_driver.h>
#include <mysql_connection.h>

#include <common/base/server_mgr.h>
#include <common/log/log.h>

#include "base/db_mgr.h"
#include "base/sub_server_mgr.h"

bool AccountMgr::init()
{
    auto subMgr = ServerMgr::get().getSubServ<SubServerMgr>();
    if (!subMgr)
    {
        LOG_ERROR("Sub manager not init.");
        return false;
    }
    auto dbMgr = subMgr->getSubMgr<DBMgr>(SubManagerType::eDB);
    if (!dbMgr)
    {
        LOG_ERROR("db manager not init.");
        return false;
    }

    auto conn = dbMgr->getMysqlConn();
    std::unique_ptr<sql::Statement> stmt(conn->createStatement());
    std::string sql("SELECT accountID, source, lastArea, "
                    " UNIX_TIMESTAMP(lastLoginTime), lastIP, areaHistory FROM `account`");
    std::unique_ptr<sql::ResultSet> res(stmt->executeQuery(std::move(sql)));
    while (res->next())
    {
        auto info = std::make_shared<AccountInfo>();
        info->accountID = res->getString(1);
        info->source    = res->getString(2);
        info->lastArea  = res->getInt(3);
        info->lastLoginTime = res->getInt64(4);
        info->lastIP    = res->getString(5);
        std::istream *stream = res->getBlob(6);
        info->areaHistory.ParseFromIstream(stream);
        delete stream;

        accounts_[info->accountID] = info;
    }

    return true;
}
